#region Summary

// 
// Owner : JackieHan 
// 
// Solution : UpdateSystem 
// 
// Project : Skomart.Update.Config 
// 
// File : ClientFileConfigItem.cs
// 
// CopyRight : Copyright © 2010-2011 Skomart Corporation, All Rights Reserved 
// 
// Summary : 客户端配置文件
// 
// History : 
//			2010-08-02 17:27:02	    Create 
// 

#endregion

#region Using

using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using Jackie.Utility;
using Jackie.Utility.CustomException;

#endregion

namespace Jackie.Update.Entities.Client
{
    /// <summary> 
    /// 客户端配置文件
    /// </summary>
    public class UpdateConfigInfo
    {
        /// <summary>
        /// 备份路径
        /// </summary>
        public string BackupPath { get; set; }
        /// <summary>
        /// 当前系统版本号
        /// </summary>
        public string CurrentVersion { get; set; }
        /// <summary>
        /// 更新日志
        /// </summary>
        public IList<UpdateLogInfo> UpdateLogs { get; set; }

        public UpdateConfigInfo(string configDirectoryPath)
        {
            var configFilePath = Path.Combine(configDirectoryPath, "UpdateConfig.xml");
            if (!File.Exists(configFilePath))
                throw new FileNotFoundException(string.Format("client config file not found!"), configFilePath);

            var doc = new XmlDocument();
            doc.Load(configFilePath);

            var backupNodes = doc.GetElementsByTagName("Backup");
            if (backupNodes.Count == 0)
                throw new NotConfigedException("the config node[Backup] not configed!", "Backup");
            BackupPath = backupNodes[0].Attributes["path"].Value;

            var versionNodes = doc.GetElementsByTagName("Version");
            if (versionNodes.Count == 0)
                throw new NotConfigedException("the config node[Version] not configed!", "Version");
            CurrentVersion = versionNodes[0].Attributes["value"].Value;

            var logNodes = doc.GetElementsByTagName("Log");
            UpdateLogs = (from XmlNode logNode in logNodes
                          select new UpdateLogInfo
                                     {
                                         Date = JackieConvertor.ToDataTimeThrowException(logNode.Attributes["date"].Value),
                                         FromVersion = logNode.Attributes["fromVersion"].Value,
                                         ToVersion = logNode.Attributes["toVersion"].Value,
                                         UpdateFiles = CreateUpdateFiles(logNode.ChildNodes),
                                     }).ToList();
        }

        private IList<UpdateFileInfo> CreateUpdateFiles(XmlNodeList updateFileNodes)
        {
            return (from XmlNode updateFileNode in updateFileNodes select new UpdateFileInfo(updateFileNode)).ToList();
        }
    }
}